import React, { useEffect, useState } from 'react';
import { TreeSelect, Spin } from 'antd';
import { getPostlist } from '@/services/components/userform';

const deepTransform = (data = []) =>
    data.map(({ positionName, positionCode, children = [] }) => ({
        value: positionCode,
        title: positionName,
        key: positionCode,
        children: children.length > 0 ? deepTransform(children) : children
    }));

const { SHOW_ALL } = TreeSelect;

const SelectPost = ({ getChildByOrganizationCode, ...restProps }) => {
    const [treeData, setTreeData] = useState([]);
    const [loading, setLoading] = useState(true);

    /* 1、获取公司列表数据 */
    const fetchData = async () => {
        try {
            const response = await getPostlist({ getChildByOrganizationCode });
            if (response.code === 10000) {
                /* 2、将数据转换为树选择组件所需格式 */
                const finalTreeData = deepTransform(response.data);
                setTreeData(finalTreeData);
            }
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchData();
    }, []);

    return (
        <Spin spinning={loading}>
            <TreeSelect
                treeNodeFilterProp="title"
                treeData={treeData}
                showCheckedStrategy={SHOW_ALL}
                {...restProps}
                style={{ height: loading ? '35px' : 'auto' }}
            />
        </Spin>
    );
};

export default SelectPost;
